﻿using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace PageOffice6_Net_Core.Controllers.FileMakerSingle
{
    public class FileMakerSingleController : Controller
    {

        private readonly IWebHostEnvironment _webHostEnvironment;

        public FileMakerSingleController(IWebHostEnvironment webHostEnvironment)
        {
            _webHostEnvironment = webHostEnvironment;
        }
        public IActionResult Index()
        {

            string url = "";
            url = _webHostEnvironment.WebRootPath + "/FileMakerSingle/doc/";
            ViewBag.url = url;
            return View();
        }

        
        public void FileMakerSingle()
        {
            string mytoken = Request.Headers["Authorization"];
            Console.WriteLine("====="+mytoken);
            PageOfficeNetCore.Word.WordDocumentWriter doc = new PageOfficeNetCore.Word.WordDocumentWriter();

            //给数据区域赋值，即把数据填充到模板中相应的位置
            doc.OpenDataRegion("PO_company").Value = "北京卓正志远软件有限公司";

            PageOfficeNetCore.FileMakerCtrl fileMakerCtrl = new PageOfficeNetCore.FileMakerCtrl(Request);

            fileMakerCtrl.SetWriter(doc);

            fileMakerCtrl.FillDocument("doc/template.doc", PageOfficeNetCore.DocumentOpenType.Word);

            Response.Body.WriteAsync(Encoding.GetEncoding("GB2312").GetBytes(fileMakerCtrl.GetHtml()));

        }

        public async Task<ActionResult> SaveDoc()
        {
            PageOfficeNetCore.FileSaver fs = new PageOfficeNetCore.FileSaver(Request, Response);
            await fs.LoadAsync();
            string webRootPath = _webHostEnvironment.WebRootPath;
            fs.SaveToFile(webRootPath + "/FileMakerSingle/doc/" + "maker" + fs.FileExtName);
            //设置自定义保存结果，用来返回给前端页面，CustomSaveResult的参数也可以是json字符串类型
            //设置文件的保存结果
            fs.CustomSaveResult = "ok";
            return fs.Close();
        }

        
    }
}